/*
  Exempel på hur authorisering fungerar i node/Express/mongodb.
  Skriver den här för att jag inte vågar ändra i main.js innan
  jag vet hur det funkar.
  Källor: 
  http://vimeo.com/17842590
  http://mongoosejs.com/docs/index.html,
  http://stackoverflow.com/questions/8051631/creating-registration-and-login-form-in-node-js-and-mongodb/8111646#8111646
  http://stackoverflow.com/questions/9900345/how-to-query-a-database-using-mongoose-in-node-js
  http://stackoverflow.com/questions/10108170/node-js-reuse-mongodb-reference
  http://stackoverflow.com/questions/5710358/how-to-get-post-query-in-express-node-js
  Alex, 28 juli
*/

var express = require('express');
var app = express();
var UserModel = require('./User').UserModel;
var db = require('./User').db;
var fs = require('fs');

var RedisStore = require('connect-redis')(express);
var secret_salt_hash = 'secret salt hash';
app.use(express.cookieParser());
app.use(express.session( {store: new RedisStore, secret: secret_salt_hash}));
app.use(express.bodyParser());

// 'middleware' concept in Express.
// Requires the user to be logged in before passing on to the next route
var requireLogin = function(req, res, next) {
    if (req.session.user)    next()

    // after logging in, redirects you to 'req.url'
    else res.redirect('/login?redir='+req.url); 
}

app.get('/', requireLogin, function(req, res) {
    res.send('User is authenticated!');
});

app.get('/login', function(req, res) {
    fs.readFile(__dirname + '/login.html',
                function(err, data) {
                    if (err) {
                        res.writeHead(500);
                        return res.end('Error loading ' + 'login.html');
                    }
                    res.end(data);
                });
});

app.post('/login', function(req, res) {
    console.log('trying to log in, name = ' + req.body.name + ', pwd = ' + req.body.password);
    //db.once('open', function callback () {
    UserModel.findOne({name: req.body.name}, function(err, result) {
        console.log("matches: " + result);
        if (result === null) {
            console.log('nope...');
            res.send('No such user!');
        }
        else if (result.password === req.body.password) {
            console.log('Yea!!!');
            req.session.user = result;
            res.send('Logged in!!!');
        }
    });
    //});
});

app.listen(8888);